package main

import (
	"gomicrov4-sharemod/services/user-service/handler"
	"gomicrov4-sharemod/services/user-service/middlewares"
	"gomicrov4-sharemod/services/user-service/utils"

	pbUser "gomicrov4-sharemod/services/user-service/proto/user"

	"github.com/go-micro/plugins/v4/registry/consul"
	"github.com/go-micro/plugins/v4/registry/etcd"
	"github.com/go-micro/plugins/v4/registry/nacos"
	"github.com/go-micro/plugins/v4/wrapper/monitoring/prometheus"
	limiter "github.com/go-micro/plugins/v4/wrapper/ratelimiter/ratelimit"
	"github.com/hashicorp/consul/api"
	"github.com/juju/ratelimit"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/urfave/cli/v2"
	"go-micro.dev/v4"
	log "go-micro.dev/v4/logger"
	"go-micro.dev/v4/registry"
)

// 编译windows版: go build -o user-service.exe main.go
// 编译linux版: go build -o user-service main.go
func main() {
	// 初始化Zap日志
	zapLogger := utils.InitZapLogger(utils.ServiceName)
	defer zapLogger.Sync()

	// 创建gRPC日志适配器
	grpcLogger := &utils.ZapGrpcLogger{
		Logger: zapLogger.Sugar(),
	}

	// 替换所有内部日志系统
	utils.ReplaceMicroLoggers(zapLogger, grpcLogger)

	var registryInstance registry.Registry
	// 获取consul、nacos、etcd配置信息
	config, err := utils.GetConfig(utils.ServiceRegistry, "yml")
	if err != nil {
		log.Fatalf("获取"+utils.ServiceRegistry+"配置信息错误: %v", err)
	}

	// ----------------- 服务注册开始 -----------------
	switch utils.ServiceRegistry {
	case "etcd":
		//集成 etcd
		registryInstance = etcd.NewRegistry(func(op *registry.Options) {
			//地址
			op.Addrs = config.GetStringSlice(utils.Env + ".addrs")
			//密码
			// etcd.Auth("gangan", "123")
		}, etcd.Auth(config.GetString(utils.Env+".username"), config.GetString(utils.Env+".password")))

	case "consul":
		// 集成consul
		registryInstance = consul.NewRegistry(
			registry.Addrs(config.GetString(utils.Env+".addrs")),
			consul.Config(&api.Config{
				Token: config.GetString(utils.Env + ".secret_id"),
			}),
		)

	case "nacos":
		//集成 nacos
		registryInstance = nacos.NewRegistry(func(op *registry.Options) {
			op.Addrs = config.GetStringSlice(utils.Env + ".addrs")
		}, nacos.WithClientConfig(constant.ClientConfig{
			NamespaceId: config.GetString(utils.Env + ".name_space_id"),
			Username:    config.GetString(utils.Env + ".username"),
			Password:    config.GetString(utils.Env + ".password"),
		}))
	}
	// ----------------- 服务注册结束 -----------------

	// 获取日志实例
	utils.Zaplog = log.DefaultLogger

	// 创建微服务
	srv := micro.NewService(
		micro.Address(utils.ServiceHost+":"+utils.ServicePort),
		micro.Name(utils.ServiceName),
		micro.Version(utils.ServiceVersion),
		micro.Registry(registryInstance),
		micro.Flags(&cli.StringFlag{
			Name:  "env",
			Usage: "The environment",
			Value: "dev",
		}),
		micro.WrapHandler(
			limiter.NewHandlerWrapper(ratelimit.NewBucketWithRate(float64(utils.Qps), int64(utils.Qps)), false),
			prometheus.NewHandlerWrapper(
				prometheus.ServiceName(utils.ServiceName),
				prometheus.ServiceVersion(utils.ServiceVersion),
			),
		),

		// 这是关键：在服务创建时设置日志器
		micro.Logger(log.DefaultLogger),

		// 注册日志中间件
		micro.WrapHandler(middlewares.ZapLogWrapper(zapLogger)),
	)

	// 初始化微服务
	srv.Init()

	// 注册用户处理
	pbUser.RegisterUserServiceHandler(srv.Server(), new(handler.UserHandler))

	// 运行服务
	if err := srv.Run(); err != nil {
		utils.Zaplog.Log(log.ErrorLevel, err)
	}
}
